package login

import (
	"fmt"
	"math/rand"
	"net/http"
	"reflect"
	"strconv"
	"time"

	"../../db/cache"
	"../../db/modes"
	"../../lib"
	"github.com/gin-gonic/gin"
)

/*
 * 描述: 学员注册
 * 路由: reg/login
 * 类型: GET
 *
 ***********************************************************************/
var lastName = []string{"づ有", "呐╰", "リ喉", "惢、", "♀對", "13u染", "(り", "赫连", "┌涐", "13u染", "sんì楐", "澹台", "、狠", "宗政"}
var firstName = []string{"伟", "刚", "勇", "毅", "俊", "峰", "强", "军", "平"}
var lastNameLen = len(lastName)
var firstNameLen = len(firstName)

func GetFullName() string {
	rand.Seed(time.Now().UnixNano())     //设置随机数种子
	var first string                     //名
	for i := 0; i <= rand.Intn(1); i++ { //随机产生2位或者3位的名
		first = fmt.Sprint(firstName[rand.Intn(firstNameLen-1)])
	}
	//返回姓名
	return fmt.Sprintf("%s%s", fmt.Sprint(lastName[rand.Intn(lastNameLen-1)]), first)
}

func UserReg(c *gin.Context) {
	var user modes.StudentInfo
	var val cache.SmsCode
	var chanat modes.ChaNat
	var us modes.Using
	if c.Query("phone") == "" {
		c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "账号不可为空"})
		return
	}
	if c.Query("pid") == "" {
		c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "请选择项目"})
		return
	}
	if c.Query("education") == "" {
		c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "请选择学历"})
		return
	}
	if c.Query("code") == "" {
		c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "请输入验证码"})
		return
	}
	chanat.Phone, _ = strconv.ParseInt(c.Query("phone"), 10, 64)

	user.Phone, _ = strconv.ParseInt(c.Query("phone"), 10, 64)

	if fage, err := user.Get(); nil == err {
		if fage == true {
			c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "该手机号已注册过了"})
			return
		}
	} else {
		c.JSON(http.StatusOK, gin.H{"err": 1, "msg": err.Error()})
		return
	}
	//us.Phone = user.Phone
	//if fage, err := us.Get(); nil == err {
	//if fage == true {
	//	c.JSON(http.StatusOK, gin.H{"err": 2,"msg": "该手机号已注册过了" })
	//	return
	//}
	//}else{
	//	c.JSON(http.StatusOK, gin.H{"err": 1,"msg": err.Error() })
	//	return
	//}
	user.Pass = c.Query("pass")
	user.File = "file.beijingyuxue.cn/1584588646/3.png"
	//user.Name = GetFullName()
	user.Name = c.Query("phone") //姓名
	code := c.Query("code")      //验证码
	if resu, err := val.Get(code); err == nil {
		fmt.Println(resu)
		if resu == "" {
			c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "验证码已过期"})
			return
		}
	}
	if _, err := user.Save(); err != nil {
		c.JSON(http.StatusOK, gin.H{"err": 0, "info": "注册失败,请联系管理员"})
		return
	}
	us.Phone = user.Phone
	if fage, err := us.Get(); err == nil {
		if fage == true {
			c.JSON(http.StatusOK, gin.H{"err": 0, "info": "注册成功！请您通过该手机号码去登陆"})
			return
		} else {
			//判断推广系统有没有该客户
			if flag, err := chanat.Get(); err == nil {
				if flag == false {
					chanat.Pro_id, _ = strconv.ParseInt(c.Query("pid"), 10, 64)
					chanat.Pro_name = c.Query("pname")
					fmt.Println(chanat.Pro_id, chanat.Pro_name)
					chanat.Education = 1
					chanat.ProWay = 15
					chanat.Courses = 1
					chanat.ProThe = 15
					chanat.ChannelId = 15
					if _, err := chanat.Save(); err != nil {
						println("首资库已存在")
						println(err.Error())
					}
				}
				println("已入推广首资库")
			} else {
				println(err.Error())
			}
		}
	}
	// UId, int64, Name, Phone string
	//token,_ := create_token( user.Id, user.Phone,user.Name )
	c.JSON(http.StatusOK, gin.H{"err": 0, "info": "注册成功！请您通过该手机号码去登陆"})
}

/*
 * 描述: 发送短信
 * 路由: reg/login
 * 类型: GET
 *
 ***********************************************************************/

type SmsCount struct {
	Count int64 `json:"count"`
}

func (this *SmsCount) ToMap() map[string]interface{} {
	m := make(map[string]interface{})
	elem := reflect.ValueOf(this).Elem()
	relType := elem.Type()
	for i := 0; i < relType.NumField(); i++ {
		m[relType.Field(i).Name] = elem.Field(i).Interface()
	}
	return m
}
func SendSms(c *gin.Context) {
	var val cache.SmsCode
	var sms lib.SmsServer
	if c.Query("pc") == "pc" {
		year, _, day := time.Now().Date()
		key := c.Query("do") + strconv.Itoa(year) + "-" + strconv.Itoa(day) + c.Query("pc") + c.Query("phone")

		mss, _ := Ur(0).HGetAll(key).Result()
		count2, _ := strconv.ParseInt(mss["Count"], 10, 64)
		if count2 >= 5 {
			if c.Query("use_code") != "use_code" {
				c.JSON(http.StatusOK, gin.H{"err": 5, "msg": "您已经输入超过五次"})
				return
			}
		}
		count2 += 1
		sms1 := SmsCount{
			Count: count2,
		}
		Ur(0).HMSet(key, sms1.ToMap()).Err()

	}

	if c.Query("phone") == "" {
		c.JSON(http.StatusOK, gin.H{"err": 2, "msg": "手机号不可为空"})
		return
	}
	phone := c.Query("phone")
	sms.Phone = phone
	//设置redis
	for i := 0; i < 20; i++ {
		code := fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))
		if fage, err := val.Exists(code); nil == err {
			if 1 == fage {
				continue
			} else {
				if err := val.Set(code, phone); err != nil {
					c.JSON(http.StatusOK, gin.H{"err": 1, "msg": err.Error()})
					return
				} else {
					// 发送验证码
					sms.Code = code
					if err := sms.Send(); err != nil {
						c.JSON(http.StatusOK, gin.H{"err": 1, "msg": "发送失败"})
						return
					}
					c.JSON(http.StatusOK, gin.H{"err": 0, "msg": "ok"})
					return
				}
			}
		} else {
			c.JSON(http.StatusOK, gin.H{"err": 3, "msg": err.Error()})
			return
		}
	}
	c.JSON(http.StatusOK, gin.H{"err": 1, "msg": "发送失败"})
}

/*
 * 描述: 项目列表
 * 路由: login/p_list
 * 类型: GET
 *
 ***********************************************************************/
func ProIdList(c *gin.Context) {

	var pro modes.Project

	list, err := pro.IdList()

	if err != nil {
		c.JSON(http.StatusOK, gin.H{"err": 1, "msg": "数据错误"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"err": 0, "date": list})
}
